﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core;
using System.Xml.Serialization;
using System.IO;

namespace COFE.Core.Profile
{
    public class LookupGuidPathParser : BasicPathParser
    {
        #region Constructor

        public LookupGuidPathParser(string lookupTablePath)
        {
            _lookupTablePath = lookupTablePath;
            LoadLookupTable();
        }

        #endregion

        #region Methods

        public void LoadLookupTable()
        {
            //XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<Guid, string>));
            //_lookupTable = new Dictionary<Guid, string>();
            //if (_lookupTablePath != null && File.Exists(_lookupTablePath))
            //    using (var fs = File.OpenRead(_lookupTablePath))
            //    {
            //        _lookupTable = (Dictionary<Guid, string>)serializer.Deserialize(fs);
            //    }
        }

        public void SaveLookupTable()
        {
            //if (_lookupTablePath == null)
            //    return;

            //XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<Guid, string>));
            //File.Delete(_lookupTablePath);
            //using (var fs = File.Create(_lookupTablePath))
            //{
            //    serializer.Serialize(fs, _lookupTable);
            //    fs.Flush();
            //}
        }

        public override IFileSystemInfo TryParsePath(IUserProfile profile, string path, ParsableType type,
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            if (type == ParsableType.Guid)
            {
                var guid = new Guid(path);
                if (!_lookupTable.ContainsKey(guid))
                    throw new KeyNotFoundException(path);
                return base.TryParsePath(profile, _lookupTable[guid], ParsableType.ParsePath, flags);
            }
            else
            {
                var retVal = base.TryParsePath(profile, path, type, flags);
                if (retVal != null && !_lookupTable.ContainsKey(retVal.GetId()))
                    _lookupTable.Add(retVal.GetId(), retVal.ParseName);
                SaveLookupTable();
                return retVal;
            }
        }

        #endregion

        #region Data

        private string _lookupTablePath = null;
        private Dictionary<Guid, string> _lookupTable = new Dictionary<Guid, string>();

        #endregion

        #region Public Properties

        #endregion

    }
}
